<?php
/**
 *+------------------
 * Lflow
 *+------------------
 * Copyright (c) 2023~2030 gitee.com/liu_guan_qing All rights reserved.本版权不可删除，侵权必究
 *+------------------
 * Author: Mr.April(405784684@qq.com)
 *+------------------
 */

namespace lflow\core;

use lflow\core\services\SurrogateServices;
use lflow\lib\util\AssertHelper;
use lflow\model\SurrogateModel;

class ManagerServices extends BaseServices
{

    public function saveOrUpdate(SurrogateModel $surrogate): void
    {
        AssertHelper::notNull($surrogate);
        $surrogate->set('state', self::STATE_ACTIVE);
        $surrogate->save();
    }

    public function deleteSurrogate(string $id): void
    {
        $surrogateServices = app()->make(SurrogateServices::class);
        $surrogate         = $surrogateServices->get($id);
        AssertHelper::notNull($surrogate);
        $surrogate->delete();
    }

    public function getSurrogate(string|array $where)
    {
        $surrogateServices = app()->make(SurrogateServices::class);
        return $surrogateServices->dao->get($surrogateServices, '*', []);
    }

    public function getSurrogates(string $operator, string $processName = ''): string
    {
        AssertHelper::notEmpty($operator);
        $where = ['operator' => $operator];
        if (!empty($processName)) {
            $where[] = ['process_name' => $processName];
        }
        $surrogates = $this->getSurrogateList($where);
        if (empty($surrogates['list']) || count($surrogates['list']) == 0) {
            return $operator;
        }
        $buffer = [];
        foreach ($surrogates['list'] as $surrogate) {
            $buffer[] = $surrogate->getData('process_name');
        }
        return implode(',', $buffer);
    }

    public function getSurrogateList(array $where, string $order = '', bool $isPage = false): array
    {
        [$page, $limit] = $this->getPageValue($isPage);
        $surrogateServices = app()->make(SurrogateServices::class);
        $list              = $surrogateServices->dao->selectList($where, '*', $page, $limit, $order, [], true);
        $count             = $surrogateServices->dao->count($where, true);
        return compact('list', 'count');
    }
}
